package com.atguigu.service;

import com.atguigu.exception.CustomException;
import com.atguigu.mapper.EmployeeMapper;
import com.atguigu.pojo.Account;
import com.atguigu.pojo.Employee;
import com.atguigu.pojo.Employee;
import com.atguigu.pojo.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;


    public void add(Employee employee) {
        String username = employee.getUsername();
        Employee dbEmployee = employeeMapper.selectByUsername(username);
        if (dbEmployee != null) {
            throw new CustomException("500", "账号已存在，请更换账号");
        }
        String no = employee.getNo();
        Employee dbEmployee1 = employeeMapper.selectByNo(no);
        if (dbEmployee1 != null) {
            throw new CustomException("500", "工号已存在，请再次确认工号！");
        }
        employee.setRole("EMP");
        employeeMapper.add(employee);
    }

    public void deleteById(Integer id) {
        employeeMapper.deleteById(id);
    }

    public void update(Employee employee) {
        employeeMapper.update(employee);
    }

    public List<Employee> selectAll(Employee employee) {
        return employeeMapper.selectAll(employee);
    }

    public Employee selectById(Integer id) {
        return employeeMapper.selectById(id);
    }

    public PageInfo<Employee> selectPage(Employee employee, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Employee> list = employeeMapper.selectAll(employee);
        return PageInfo.of(list);
    }


    public void deleteBatch(List<Integer> ids) {
        for(Integer id : ids) {
            employeeMapper.deleteById(id);
        }
    }

    public Employee login(Account account) {
        String username = account.getUsername();
        Employee dbEmployee = employeeMapper.selectByUsername(username);
        if(dbEmployee == null) {//查不到
            throw new CustomException("500", "账号不存在！");
        }
        String password = account.getPassword();
        if(!dbEmployee.getPassword().equals(password)) {
            throw new CustomException("500", "账号或者密码错误！");
        }
        return dbEmployee;
    }

    public void register(Employee employee) {
//        throw new CustomException("500", "账号已存在，请更换账号");
        this.add(employee);
    }
    public void updatePassword(Account account) {
        Integer id = account.getId();
        Employee dbEmployee = employeeMapper.selectById(id);
        if(!dbEmployee.getPassword().equals(account.getPassword())) {
            throw new CustomException("500", "原密码错误！");
        }
        dbEmployee.setPassword(account.getNewPassword());
        this.update(dbEmployee);
    }
}
